package org.example.mqtt;

import com.hivemq.client.mqtt.datatypes.MqttQos;
import com.hivemq.client.mqtt.mqtt5.Mqtt5AsyncClient;
import com.hivemq.client.mqtt.mqtt5.Mqtt5Client;

/**
 * @author scout.du
 * @date 2025/10/14 11:06
 **/
public class Client5V1Start {

    public static void main(String[] args) {

        // 1. 创建异步 MQTT 客户端（MQTT 3）
//        Mqtt3AsyncClient client = Mqtt3Client.builder()
//                .identifier("java-client-01")   // Client ID
//                .serverHost("localhost")        // Broker 地址
//                .serverPort(1883)               // WebSocket 端口
//                .buildAsync();

        Mqtt5AsyncClient client = Mqtt5Client.builder()
                .serverHost("localhost")
                .serverPort(1883)
                .build().toAsync();

        // 2. 连接 Broker
        client.connect()
                .whenComplete((connAck, throwable) -> {
                    if (throwable != null) {
                        System.err.println("连接失败: " + throwable.getMessage());
                    } else {
                        System.out.println("已连接到 HiveMQ Broker");

                        // 3. 订阅 topic
                        client.subscribeWith()
                                .topicFilter("testtopic2")
                                .qos(MqttQos.AT_LEAST_ONCE)
                                .callback(publish -> {
                                    System.out.println("收到消息: " + new String(publish.getPayloadAsBytes()));
                                })
                                .send();

                        // 4. 发布消息
                        client.publishWith()
                                .topic("testtopic1")
                                .payload("Hello HiveMQ from Java!".getBytes())
                                .qos(MqttQos.AT_LEAST_ONCE)
                                .send()
                                .whenComplete((pub, ex) -> {
                                    if (ex != null) {
                                        System.err.println("消息发送失败: " + ex.getMessage());
                                    } else {
                                        System.out.println("消息已发送成功");
                                    }
                                });
                    }
                });

        // 阻止主线程退出（仅测试用）
        try {
            Thread.sleep(50000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 5. 断开连接
        client.disconnect();
    }
}
